package com.ruibang.glass.apigateway.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruibang.glass.apigateway.config.JwtFilterConfig;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.Serializable;
import java.util.List;

/**
 * jwt Token过滤器
 */
@Slf4j
@Component
public class JwtTokenFilter implements GlobalFilter, Ordered {

    public static int APP_TOKEN_CODE_EXPIRE = 30 * 24 * 60 * 60;

    public static int PC_TOKEN_CODE_EXPIRE = 30 * 24 * 60 * 60;

    private static String CHARACTER_TYPE_UTF8 = "UTF-8";

    private static String CHECK_LOGIN_PARAM_INFO = "CHECK_LOGIN_PARAM_INFO";

    private static String LOGIN_FAILED_MESSAGE = "用户未登录或登录失效";

    @Autowired
    private JwtFilterConfig jwtFilterConfig;

//    @Autowired
//    private RedisSingleService redisService;

    @Autowired
    private RedisSingleService redisService;


    /**
     * @param uri
     * @return true：需要过滤，false：不需要过滤
     * @Title: isExcludedRoute
     * @Description: url是否需要过滤,
     */
    private boolean isExcludedRoute(String uri) {
        // 排除的URL
        List<String> excludeds = jwtFilterConfig.getExcludeds();
        // 排除的后缀
        List<String> suffixes = jwtFilterConfig.getSuffixes();
        // 过滤css和js等静态资源
        if (!CollectionUtils.isEmpty(suffixes)) {
            for (String suffix : suffixes) {
                if (uri.contains(suffix)) {
                    return false;
                }
            }
        }

        if (!CollectionUtils.isEmpty(excludeds)) {
            for (String exclude : excludeds) {
                // 判断当前URL是否与配置URL相同
                if (uri.contains(exclude)) {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        String requestUrl = request.getPath().toString();
        ServerHttpResponse response = exchange.getResponse();
        if (isExcludedRoute(requestUrl)) {
            String token = exchange.getRequest().getHeaders().getFirst("token");

            //用户未登录或登录失效
            if (StringUtils.isBlank(token)) {
                return returnMsg("token 不存在", response);

            } else {
                if (redisService.hasKey(token)) {
                    Serializable serializable = redisService.get(token);
                    if (serializable == null || StringUtils.isBlank(serializable.toString())) {
                        return returnMsg(LOGIN_FAILED_MESSAGE, response);
                    }
                    String json = serializable.toString();
                    GlobalUser globalUser = JSON.parseObject(json, GlobalUser.class);
                    if (globalUser == null) {
                        return returnMsg(LOGIN_FAILED_MESSAGE, response);
                    }
                    /*String currentIp = request.getRemoteAddress().getAddress().getHostAddress();
                    if(!currentIp.equals(globalUser.getIpAddress())){
                        return returnMsg("系统操作IP不一致，请重新登录",response);
                    }*/

                    if (redisService.hasKey(CHECK_LOGIN_PARAM_INFO)) {
                        Serializable userStr = redisService.get(CHECK_LOGIN_PARAM_INFO);
                        if (userStr != null && StringUtils.isNotBlank(userStr.toString())) {
                            List<String> userIds = JSON.parseArray(userStr.toString(), String.class);
                            if (!checkByUserIds(globalUser.getUserId(), userIds)) {
                                return returnMsg(LOGIN_FAILED_MESSAGE, response);
                            }
                        } else {
                            return returnMsg(LOGIN_FAILED_MESSAGE, response);
                        }
                    } else {
                        return returnMsg(LOGIN_FAILED_MESSAGE, response);
                    }

                    //更新超时时间
                    redisService.set(token, json, PC_TOKEN_CODE_EXPIRE);

                } else {
                    return returnMsg(LOGIN_FAILED_MESSAGE, response);
                }
            }
        }

        return chain.filter(exchange);
    }

    public Mono<Void> returnMsg(String msg, ServerHttpResponse response) {
        try {
            JSONObject message = new JSONObject();
            message.put("code", 9999);
            message.put("message", msg);
            byte[] bits = message.toString().getBytes(CHARACTER_TYPE_UTF8);
            DataBuffer buffer = response.bufferFactory().wrap(bits);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add("Content-Type", "text/json;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        return null;
    }

    @Override
    public int getOrder() {
        return -100;
    }

    /**
     * 效验用户是否存在
     *
     * @param currentUser
     * @param userIds
     * @return
     */
    private boolean checkByUserIds(String currentUser, List<String> userIds) {
        boolean flag = false;
        for (String userId : userIds) {
            if (userId.equals(currentUser)) {
                flag = true;
                break;
            }
        }
        return flag;
    }

}